<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="module">
/**
 * This import the entire data export logic for ARC and dumps all the user data
 * into a temporary folder (in the system's TMP path).
 * 
 * Then it reports the operation finished to the IO process so it can run the import window
 * and import the data into the application.
 */
 import { PouchDB, ExportProcessor, ExportFactory } from 'web-module:../web_modules/index.js';

window.PouchDB = PouchDB;
const { ipcRenderer } = require('electron');
const fs = require('fs-extra');

ipcRenderer.send('data-transport-ready', 'server');

/**
 * @param {any} e
 * @param {string} storeLocation
 * @return Promise<void>
 */
async function start(e, storeLocation) {
  console.info('Starting data migration');
  try {
    const factory = new ExportFactory();
    const data = /** @type any[] */ (await factory.getExportData({
      authdata: true,
      clientcertificates: true,
      cookies: true,
      history: true,
      hostrules: true,
      projects: true,
      requests: true,
      variables: true,
      websocketurlhistory: true,
      urlhistory: true,
    }));
    if (!data || !data.length) {
      ipcRenderer.send('server-db-no-data');
      return;
    }
    const withData = data.some((item) => Array.isArray(item.data) && !!item.data.length);
    if (!withData) {
      ipcRenderer.send('server-db-no-data');
      return;
    }
    const config = {
      appVersion: '16.0.0-data-migration',
      kind: 'ARC#AllDataExport',
    };
    const processor = new ExportProcessor(false);
    const exportObject = await processor.createExportObject(data, config);
    await fs.outputJson(storeLocation, exportObject);
    ipcRenderer.send('server-db-finished');
  } catch (e) {
    console.error(e);
    ipcRenderer.send('db-error', e.message, e.stack);
  }
}
ipcRenderer.once('server-start', start);
</script>
</body>
</html>
